<?php

class Damages_Methods_Request_Edit_User extends Damages_Methods_Request {

  /**
   *
   * @var Damages_Methods_Data_User_Edit 
   */
  public $obj;

  public function __construct($params) {
    $this->obj = new Damages_Methods_Data_User_Edit($params->obj);
    parent::__construct($params);
  }

  /**
   * 
   * @return \Damages_Methods_Data_User_Detailed
   * @throws Damages_Exception_App
   * @throws Exception
   */
  public function process() {
    if (!Damages_Auth::getInstance()->checkPermission(Damages_Auth::PERMISSION_ADMIN))
      throw new Damages_Exception_App(Damages_Codes::ACCESS_DENIED);
    $con = Propel::getConnection(Damages_Config::getInstance()->datasource);
    $con->beginTransaction();
    try {
      if ($this->obj->id) {
        $user = DamagesUsersQuery::create()->findOneById($this->obj->id);
        if (!$user instanceof DamagesUsers)
          throw new Damages_Exception_App(Damages_Codes::DB_OBJECT_NOT_FOUND, array($this->obj->id));
        DamagesUserDealersQuery::create()->filterByUserId($this->obj->id)->delete();
      } else {
        $user = new DamagesUsers();
      }
      $user->setFirstName($this->obj->firstName);
      $user->setLastName($this->obj->lastName);
      $user->setEmail($this->obj->email);
      $user->setPosition($this->obj->position);
      $user->setPhone($this->obj->phone);
      $user->setPhoneFax($this->obj->phoneFax);
      $user->setPhoneMobile($this->obj->phoneMobile);
      $user->setPermissionId($this->obj->permission->id);
      foreach ($this->obj->dealers as $dealer) {
        $userDealer = new DamagesUserDealers();
        $userDealer->setDealerId($dealer->id);
        $user->addUserDealers($userDealer);
      }
      $user->save();
      $con->commit();
    } catch (Exception $exc) {
      $con->rollBack();
      throw $exc;
    }

    $response = new Damages_Methods_Response_SaveUser($user);

    return $response;
  }

}